import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import '../models/counter_model.dart';

/// 计数器详情屏幕
/// 展示如何在不同屏幕间共享Scoped Model状态
class CounterDetailScreen extends StatelessWidget {
  const CounterDetailScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Counter Details'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          // 在AppBar中显示当前计数
          ScopedModelDescendant<CounterModel>(
            builder: (context, child, model) {
              return Center(
                child: Padding(
                  padding: const EdgeInsets.only(right: 16.0),
                  child: Text(
                    '${model.counter}',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              );
            },
          ),
        ],
      ),
      body: const SingleChildScrollView(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _DetailedCounterInfo(),
            SizedBox(height: 16),
            _CounterHistory(),
            SizedBox(height: 16),
            _QuickActions(),
            SizedBox(height: 24), // 底部额外空间
          ],
        ),
      ),
    );
  }
}

/// 详细的计数器信息
class _DetailedCounterInfo extends StatelessWidget {
  const _DetailedCounterInfo();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ScopedModelDescendant<CounterModel>(
          builder: (context, child, model) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Detailed Information',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 16),

                // 当前值
                _buildInfoRow(
                  'Current Value',
                  '${model.counter}',
                  Icons.numbers,
                  Colors.blue,
                ),

                // 状态
                _buildInfoRow(
                  'Status',
                  model.counterStatus,
                  Icons.info_outline,
                  _getStatusColor(model.counterStatus),
                ),

                // 用户
                _buildInfoRow(
                  'User',
                  model.username,
                  Icons.person_outline,
                  Colors.green,
                ),

                // 是否为偶数
                _buildInfoRow(
                  'Is Even',
                  model.counter % 2 == 0 ? 'Yes' : 'No',
                  model.counter % 2 == 0 ? Icons.check_circle : Icons.cancel,
                  model.counter % 2 == 0 ? Colors.green : Colors.red,
                ),

                // 距离下一个里程碑
                _buildInfoRow(
                  'Next Milestone',
                  _getNextMilestone(model.counter),
                  Icons.flag_outlined,
                  Colors.orange,
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value, IconData icon, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, color: color, size: 24),
          const SizedBox(width: 12),
          Expanded(child: Text(label, style: const TextStyle(fontSize: 16))),
          Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'Zero':
        return Colors.grey;
      case 'Low':
        return Colors.green;
      case 'Medium':
        return Colors.orange;
      case 'High':
        return Colors.red;
      default:
        return Colors.blue;
    }
  }

  String _getNextMilestone(int current) {
    final milestones = [10, 25, 50, 100, 250, 500, 1000];
    for (int milestone in milestones) {
      if (current < milestone) {
        return '${milestone - current} to reach $milestone';
      }
    }
    return 'You\'ve reached all milestones!';
  }
}

/// 计数器历史记录（模拟）
class _CounterHistory extends StatelessWidget {
  const _CounterHistory();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Statistics',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            ScopedModelDescendant<CounterModel>(
              builder: (context, child, model) {
                return Column(
                  children: [
                    // 进度条显示
                    _buildProgressSection(
                      'Progress to 100',
                      model.counter,
                      100,
                    ),
                    const SizedBox(height: 12),
                    _buildProgressSection(
                      'Progress to 500',
                      model.counter,
                      500,
                    ),
                    const SizedBox(height: 12),
                    _buildProgressSection(
                      'Progress to 1000',
                      model.counter,
                      1000,
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressSection(String title, int current, int target) {
    final progress = (current / target).clamp(0.0, 1.0);
    final percentage = (progress * 100).toInt();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              flex: 2,
              child: Text(title, style: const TextStyle(fontSize: 14)),
            ),
            Expanded(
              flex: 1,
              child: Text(
                '$current / $target ($percentage%)',
                textAlign: TextAlign.right,
                style: const TextStyle(fontSize: 12),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
        const SizedBox(height: 4),
        LinearProgressIndicator(
          value: progress,
          backgroundColor: Colors.grey[300],
          valueColor: AlwaysStoppedAnimation<Color>(
            progress == 1.0 ? Colors.green : Colors.blue,
          ),
        ),
      ],
    );
  }
}

/// 快速操作区域
class _QuickActions extends StatelessWidget {
  const _QuickActions();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Quick Actions',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 预设值按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: [
                _buildPresetButton(context, 'Set to 10', 10),
                _buildPresetButton(context, 'Set to 25', 25),
                _buildPresetButton(context, 'Set to 50', 50),
                _buildPresetButton(context, 'Set to 100', 100),
              ],
            ),

            const SizedBox(height: 16),

            // 操作按钮
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: () {
                      CounterModel.of(context).reset();
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Counter reset to 0')),
                      );
                    },
                    icon: const Icon(Icons.refresh),
                    label: const Text('Reset'),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: ScopedModelDescendant<CounterModel>(
                    builder: (context, child, model) {
                      return ElevatedButton.icon(
                        onPressed: model.isLoading
                            ? null
                            : () => model.incrementAsync(),
                        icon: model.isLoading
                            ? const SizedBox(
                                width: 16,
                                height: 16,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                ),
                              )
                            : const Icon(Icons.cloud_upload),
                        label: Text(
                          model.isLoading ? 'Loading...' : 'Async +1',
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPresetButton(BuildContext context, String label, int value) {
    return ScopedModelDescendant<CounterModel>(
      builder: (context, child, model) {
        final isCurrentValue = model.counter == value;
        return OutlinedButton(
          onPressed: isCurrentValue
              ? null
              : () {
                  // 直接设置值（这里我们需要添加一个新方法）
                  final difference = value - model.counter;
                  if (difference > 0) {
                    model.addMultiple(difference);
                  } else if (difference < 0) {
                    // 重置然后添加
                    model.reset();
                    model.addMultiple(value);
                  }

                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Counter set to $value')),
                  );
                },
          style: OutlinedButton.styleFrom(
            backgroundColor: isCurrentValue ? Colors.grey[200] : null,
          ),
          child: Text(label),
        );
      },
    );
  }
}
